﻿using Batman.Cms.Loaders;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Options;
using System.IO;
using System.Linq;

namespace Batman.Cms
{
    public class PluginRazorViewEngineOptionsSetup : ConfigureOptions<RazorViewEngineOptions>
    {
        public PluginRazorViewEngineOptionsSetup(IHostingEnvironment hostingEnvironment) :
            base(options => ConfigureRazor(options, hostingEnvironment))
        {

        }
        private static void ConfigureRazor(RazorViewEngineOptions options, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                options.FileProviders.Add(new DeveloperViewFileProvider(env));
            }
            PluginLoader.GetPlugins(null).ToList().ForEach(assembly =>
            {
                var reference = MetadataReference.CreateFromFile(assembly.Assembly.Location);
                options.AdditionalCompilationReferences.Add(reference);
            });
            PluginLoader.GetPlugins(null).ToList().ForEach(m =>
            {
                var directory = new DirectoryInfo(m.Path);
                if (env.IsDevelopment())
                {
                    options.ViewLocationFormats.Add($"/Porject.RootPath/Plugins/{directory.Name}" + "/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
                    options.ViewLocationFormats.Add($"/Porject.RootPath/Plugins/{directory.Name}" + "/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
                    options.ViewLocationFormats.Add($"/Porject.RootPath/Plugins/{directory.Name}" + "/Views/{0}" + RazorViewEngine.ViewExtension);
                }
                else
                {
                    options.ViewLocationFormats.Add($"/Plugins/{directory.Name}" + "/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
                    options.ViewLocationFormats.Add($"/Plugins/{directory.Name}" + "/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
                    options.ViewLocationFormats.Add($"/Plugins/{directory.Name}" + "/Views/{0}" + RazorViewEngine.ViewExtension);
                }
            });
            options.ViewLocationFormats.Add("/Views/{0}" + RazorViewEngine.ViewExtension);
        }
    }
}
